package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.security.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) throws Exception {
        AjaxResult ajax = AjaxResult.success();
        String userName = RsaUtils.decryptByPrivateKey(loginBody.getUsername());
        String password = RsaUtils.decryptByPrivateKey(loginBody.getPassword());
        if (loginService.lockLoginFor5times(userName, 5)) {
            return AjaxResult.error("账号登录失败，已锁定");
        }
        // 生成短信密钥
        String smsKey = loginService.login(userName, password, loginBody.getCode(),
                loginBody.getUuid());
        if (Constants.ERROR_PHONE_NOT_BIND.equals(smsKey)) {
            return AjaxResult.error("用户未绑定手机或绑定手机不正确，请联系管理员");
        }
        if (RuoYiConfig.isNeedCheckSms()) {
            ajax.put(Constants.SMS_KEY, smsKey);
        } else {
            ajax.put(Constants.TOKEN, smsKey);
        }
        ajax.put(Constants.CHECK_SMS, RuoYiConfig.isNeedCheckSms());
        return ajax;
    }

    /**
     * 短信校验
     *
     * @param smsCheckMap 短信验证消息
     * @return 结果
     */
    @PostMapping("/smsCheck")
    public AjaxResult smsCheck(@RequestBody HashMap<String, Object> smsCheckMap) throws Exception {
        AjaxResult ajax = AjaxResult.success();
        String smsKey = (String) smsCheckMap.get("smsKey");
        String smsValue = (String) smsCheckMap.get("smsValue");
        // 返回token
        if (smsValue == null || "".equals(smsValue.trim())) {
            return AjaxResult.error("短信验证码不正确");
        }
        String token = loginService.smsCheck(smsKey, smsValue);
        if (token != null) {
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } else {
            return AjaxResult.error("短信验证码不正确");
        }
    }

    /**
     * 重发短信
     *
     * @param smsCheckMap 短信验证消息
     * @return 结果
     */
    @PostMapping("/resendSms")
    public AjaxResult resendSms(@RequestBody HashMap<String, Object> smsCheckMap) throws Exception {
        AjaxResult ajax = AjaxResult.success();
        String smsKey = (String) smsCheckMap.get("smsKey");
        // 返回token
        if (smsKey == null || "".equals(smsKey.trim())) {
            return AjaxResult.error("发送异常，请联系管理员");
        }
        String sendResult = loginService.resendSms(smsKey);
        if (sendResult == null || "".equals(sendResult.trim())) {
            return AjaxResult.error("发送异常，请联系管理员");
        }
        if (Constants.ERROR_SMS_KEY_MAP.equals(sendResult)) {
            return AjaxResult.error("未登录，手机号码验证失败");
        }
        if (Constants.ERROR_PHONE_NOT_BIND.equals(smsKey)) {
            return AjaxResult.error("用户未绑定手机或绑定手机不正确，请联系管理员");
        }
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
